<template>
  <div class="app-container">
    <div class="flex-between">
      <div class="flex-between">
        <el-button
          v-if="$store.state.user.roles === 'admin' || $store.state.user.roles === 'godown'"
          type="primary"
          @click="handleInMedicine"
        >药品入库</el-button>
        <el-button
          type="danger"
          @click="handleOutMedicine"
        >药品出库</el-button>
      </div>
      <el-input
        v-model="search"
        class="search-main"
        placeholder="请输入药品名字查询"
        prefix-icon="el-icon-search"
        @keyup.enter.native="HandleSearch"
      />
    </div>
    <el-table
      ref="medicineList"
      :data="medicineList"
      style="width: 100%;margin-top:30px;"
    >
      <el-table-column
        align="center"
        label="药品名称"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="药品编号"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="药品库存"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.number }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="厂家"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.factory }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="售价"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.sellingPrice }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="$store.state.user.roles === 'admin' "
        align="center"
        label="进价"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.purchasePrice }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="提成方式"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row. commissionTypeC }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="提成"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row. commission }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="规格"
        width=""
      >
        <template slot-scope="scope">
          {{ scope.row.spec }}
        </template>
      </el-table-column>
      <el-table-column
        align="header-center"
        label="最后一次录入时间"
      >
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope)"
          >修改</el-button>
          <template v-if="scope.row.disable === 1">
            <el-button
              type="success"
              size="small"
              @click="handleDelete2(scope)"
            >解禁</el-button>
          </template>
          <template v-if="scope.row.disable === 0">
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope)"
            >禁用</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      :current-page="pageNum"
      :page-size="pageSize"
      layout="total,sizes,  prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :visible.sync="dialogRuku"
      :title="'入库操作'"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClickRuku"
      >
        <el-tab-pane
          label="入库原有药品"
          name="first"
        >
          <el-form
            :model="medicine"
            label-width="80px"
            label-position="left"
          >
            <el-form-item
              label="选择"
              required
            >
              <el-input
                v-model="medicine.name"
                class="medicine-input"
                placeholder="请选择药品"
                suffix-icon="el-icon-bank-card"
                @click.native="dialogMedicine=true"
              />
            </el-form-item>
            <el-form-item label="编号">
              <el-input
                v-model="medicine.code"
                placeholder="请输入药品编号"
                :disabled="true"
              />
            </el-form-item>
            <el-form-item
              label="数量"
              required
            >
              <el-input
                v-model="medicine.number"
                placeholder="请输入进货数量"
                type="number"
                required
              />
            </el-form-item>
            <el-form-item label="厂家">
              <el-input
                v-model="medicine.factory"
                placeholder="请输入厂家名称"
                :disabled="true"
              />
            </el-form-item>
            <el-form-item label="售价">
              <el-input
                v-model="medicine.sellingPrice"
                placeholder="请输入药品售价"
                :disabled="true"
                required
              />
            </el-form-item>
            <el-form-item
              label="进价"
              required
            >
              <el-input
                v-model="medicine.purchasePrice"
                placeholder="请输入药品进价"
              />
            </el-form-item>
            <el-form-item label="规格">
              <el-input
                v-model="medicine.spec"
                placeholder="请输入规格"
              />
            </el-form-item>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogRuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicine"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          label="入库新药品"
          name="second"
        >
          <el-form
            ref="rukuNewForm"
            :model="medicine"
            label-width="80px"
            label-position="left"
            :rules="rukuRules"
          >
            <el-form-item
              label="名称"
              prop="name"
            >
              <el-input
                v-model="medicine.name"
                placeholder="请输入药品名称"
              />
            </el-form-item>
            <el-form-item label="编号">
              <el-input
                v-model="medicine.code"
                placeholder="请输入药品编号"
              />
            </el-form-item>
            <el-form-item
              label="数量"
              prop="number"
            >
              <el-input
                v-model="medicine.number"
                type="number"
                placeholder="请输入进货数量"
              />
            </el-form-item>
            <el-form-item label="是否预警">
              <el-radio-group v-model="medicine.earlyWarning">
                <el-radio :label="0">
                  不开启报警
                </el-radio>
                <el-radio :label="1">
                  开启报警
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="medicine.earlyWarning === 1" label="报警上限">
              <el-input
                v-model="medicine.upperLimit"
                type="number"
                placeholder="数量超出上限后会报警 "
              />
            </el-form-item>
            <el-form-item v-if="medicine.earlyWarning === 1" label="报警下限">
              <el-input
                v-model="medicine.lowerLimit"
                type="number"
                placeholder="数量小于下限后悔报警 "
              />
            </el-form-item>
            <el-form-item label="厂家">
              <el-input
                v-model="medicine.factory"
                placeholder="请输入厂家名称"
              />
            </el-form-item>
            <el-form-item
              label="普通售价"
              required
            >
              <el-input
                v-model="medicine.sellingPrice"
                placeholder="销售价格"
              />
            </el-form-item>
            <el-form-item
              v-if="medicine.priceVOList.length == 0"
              label="会员售价"
            >
              <el-button
                icon="el-icon-plus"
                style="margin-left:15px"
                @click="handleAddH()"
              />
            </el-form-item>
            <div
              v-for="(item,i) in medicine.priceVOList"
              :key="i"
            >
              <el-form-item
                :label="(i+1)+'级会员售价'"
                prop="sellingPrice"
                label-width="100px"
              >
                <el-col :span="8">
                  <el-input
                    v-model="item.sellingPrice"
                    placeholder="请输入药品售价"
                    required
                    width="80%"
                    :disabled="i+1<medicine.priceVOList.length"
                    @change="handlerChangeShou"
                  />
                </el-col>
                <el-button
                  v-if="i+1==medicine.priceVOList.length"
                  icon="el-icon-plus"
                  style="margin-left:15px"
                  @click="handleH(i,1)"
                />
                <el-button
                  v-if="i+1==medicine.priceVOList.length && i!==0"
                  icon="el-icon-minus"
                  style="margin-left:15px"
                  @click="handleH(i,2)"
                />
              </el-form-item>
            </div>
            <el-form-item
              label="进价"
              prop="purchasePrice"
            >
              <el-input
                v-model="medicine.purchasePrice"
                type="number"
                placeholder="请输入药品进价"
                required
                @change="handlerChangeJin"
              />
            </el-form-item>

            <el-form-item label="提成方式">
              <el-radio-group v-model="medicine.commissionType">
                <el-radio :label="0">
                  无提成
                </el-radio>
                <el-radio :label="1">
                  比例提成
                </el-radio>
                <el-radio :label="2">
                  固定提成
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item v-if="medicine.commissionType === 2" label="提成数额">
              <el-input
                v-model="medicine.commissionAmount"
                placeholder="请输入药品销售提成 "
              />
            </el-form-item>
            <el-form-item v-if="medicine.commissionType === 1" label="提成比例">
              <el-input
                v-model="medicine.commission"
                placeholder="请输入药品比例提成的小数"
              />
            </el-form-item>
            <el-form-item label="规格">
              <el-input
                v-model="medicine.spec"
                placeholder="请输入规格"
              />
            </el-form-item>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogRuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicine"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
    <el-dialog
      :visible.sync="dialogChuku"
      :title="'出库操作'"
      width="75%"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClickChuku"
      >
        <el-tab-pane
          label="根据药方出库"
          name="first"
        >
          <el-form
            :model="prescription"
            label-width="80px"
            label-position="left"
          >
            <el-row>
              <el-form-item
                label="药方"
                required
              >
                <el-input
                  v-model="medicine.shortName"
                  class="medicine-input"
                  placeholder="请选择药方"
                  suffix-icon="el-icon-bank-card"
                  @click.native="dialogPrescription=true"
                />
              </el-form-item>
              <el-col :span="8">
                <el-form-item label="售价">
                  <el-input
                    v-model="prescription.amount"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="医师姓名">
                  <!-- <h2>{{prescription.adminInfoVO.name}}</h2> -->
                  <el-input
                    v-model="prescription.adminInfoVO.name"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="患者姓名">
                  <el-input
                    v-model="prescription.userInfoVO.username"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-form-item label="会员等级">
                <el-input
                  v-model="prescription.userInfoVO.level"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item label="处方价格">
                <el-input
                  v-model="prescription.amount"
                  :disabled="true"
                />
              </el-form-item>
              <el-form-item
                label="挂号费用"
                required
              >
                <el-input
                  v-model="pay.registrationFee"
                  type="number"
                  placeholder="请输入挂号费用"
                  @input="guahao"
                />
              </el-form-item>
              <el-form-item
                label="应付费用"
                required
              >
                <el-input
                  v-model="pay.allPrice"
                  placeholder=""
                  :disabled="true"
                />
              </el-form-item>
              <div
                v-for="(item2,i) in payArr"
                :key="i"
              >

                <el-form-item label="支付方式">
                  <el-select
                    v-model="item2.method"
                    placeholder="请选择支付方式"
                  >
                    <el-option
                      v-for="item in payMethodList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <el-button
                    :icon="i==0?'el-icon-plus':'el-icon-minus'"
                    style="margin-left:15px"
                    @click="handleP(i)"
                  />
                </el-form-item>

                <el-form-item label="支付价格">
                  <el-input
                    v-model="item2.amount"
                    placeholder="请输入支付价格"
                  > <template slot="append">元</template></el-input>
                </el-form-item>
              </div>
              <el-form-item label="备注">
                <el-input
                  v-model="medicine.remark"
                  style="width:50%"
                  type="textarea"
                  :rows="4"
                  resize="none"
                  placeholder="请输入备注"
                />
              </el-form-item>
            </el-row>
            </el-form-item>

            <el-table
              :data="prescriptionMedicineList"
              style="width: 100%;margin-bottom:20px"
            >
              <el-table-column
                prop="name"
                label="名称"
                width="180"
              />
              <el-table-column
                prop="number"
                label="数量"
                width="180"
              />
              <el-table-column
                prop="sellingPrice"
                label="单价"
              />
              <el-table-column
                prop="allPrice"
                label="总价"
              />
            </el-table>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogChuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicineChuku('yaofang')"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          v-if="$store.state.user.roles !== 'godown'"
          label="零售出库"
          name="second"
        >
          <el-form
            :model="medicine"
            label-width="80px"
            label-position="left"
          >
            <el-form-item label="是否会员">
              <el-switch
                v-model="isUser"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="changeUser"
              />
            </el-form-item>
            <div v-if="isUser">
              <el-form-item label="手机号">
                <el-input
                  v-model="user.mobile"
                  style="width:50%"
                  placeholder="请输入会员手机号"
                />
                <el-button @click="getUser">确定</el-button>
                <el-button @click="handleSelectUser">选择会员</el-button>
              </el-form-item>
              <el-col :span="8">
                <el-form-item label="手机号">
                  <el-input
                    v-model="user.mobile"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="会员姓名">
                  <!-- <h2>{{prescription.adminInfoVO.name}}</h2> -->
                  <el-input
                    v-model="user.username"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="会员等级">
                  <el-input
                    v-model="user.level"
                    :disabled="true"
                  />
                </el-form-item>
              </el-col>
            </div>
            <dnd-list
              :list1="list1"
              :prescription-id="prescriptionNewId"
              list1-title="开具的药品"
              list2-title="所有药品"
              :level="level"
              @selectList2="selectList2"
              @setPrice="getPrice"
            />
            <div
              v-for="(item2,i) in payArr"
              :key="i"
            >

              <el-form-item label="支付方式">
                <el-select
                  v-model="item2.method"
                  placeholder="请选择支付方式"
                >
                  <el-option
                    v-for="item in payMethodList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-button
                  :icon="i==0?'el-icon-plus':'el-icon-minus'"
                  style="margin-left:15px"
                  @click="handleP(i)"
                />
              </el-form-item>

              <el-form-item label="支付价格">
                <el-input
                  v-model="item2.amount"
                  style="width:200px"
                  placeholder="请输入支付价格"
                > <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </div>
            <el-form-item label="备注">
              <el-input
                v-model="medicine.remark"
                style="width:50%"
                type="textarea"
                :rows="4"
                resize="none"
                placeholder="请输入备注"
              />
            </el-form-item>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogChuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicineChuku('lingshou')"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane
          v-if="$store.state.user.roles === 'admin' || $store.state.user.roles === 'godown'"
          label="其他出库"
          name="qita"
        >
          <el-form
            :model="medicine"
            label-width="80px"
            label-position="left"
          >
            <dnd-list
              :list1="list1"
              :prescription-id="prescriptionNewId"
              list1-title="出库的药品"
              list2-title="所有药品"
              @selectList2="selectList2"
            />
            <el-form-item label="备注">
              <el-input
                v-model="medicine.remark"
                style="width:50%"
                type="textarea"
                :rows="4"
                resize="none"
                placeholder="请输入备注"
              />
            </el-form-item>
            <div style="text-align:right;">
              <el-button
                type="danger"
                @click="dialogChuku=false"
              >取消</el-button>
              <el-button
                type="primary"
                @click="confirmMedicineChuku"
              >确定</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>

    </el-dialog>
    <el-dialog
      class="select-medicine-dialog"
      :visible.sync="dialogMedicine"
      :title="'选择药品'"
      width="80%"
      append-to-body
    >
      <mediceSelect
        @cancel="medicineCancel"
        @confirm="selectMedicine"
      />
    </el-dialog>
    <el-dialog
      class="select-medicine-dialog"
      :visible.sync="dialogPrescription"
      :title="'选择药方'"
      width="80%"
      append-to-body
    >
      <prescriptionSelect
        :payment="'0'"
        :type="'1'"
        @cancel="prescriptionCancel"
        @confirm="selectPrescription"
      />
    </el-dialog>
    <el-dialog
      class="select-medicine-dialog"
      :visible.sync="dialogUser"
      :title="'选择用户'"
      width="80%"
      :close-on-click-modal="false"
      append-to-body
    >
      <user
        @confirm="selectUser"
        @handleCancel="cancelUser"
      />
    </el-dialog>
    <el-dialog
      :visible.sync="dialogBianji"
      :title="'编辑操作'"
    >
      <el-tabs
        v-model="activeName"
        @tab-click="handleClickRuku"
      >
        <el-form
          :model="medicine"
          label-width="80px"
          label-position="left"
        >
          <el-form-item label="名称">
            <el-input
              v-model="medicine.name"
              placeholder="请输入药品名称"
            />
          </el-form-item>
          <el-form-item label="编号">
            <el-input
              v-model="medicine.code"
              placeholder="请输入药品编号"
            />
          </el-form-item>
          <el-form-item
            label="库存"
            required
          >
            <el-input
              v-model="medicine.number"
              placeholder="库存"
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="厂家">
            <el-input
              v-model="medicine.factory"
              placeholder="请输入厂家名称"
            />
          </el-form-item>
          <el-form-item label="是否预警">
            <el-radio-group v-model="medicine.earlyWarning">
              <el-radio :label="0">
                不开启报警
              </el-radio>
              <el-radio :label="1">
                开启报警
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="medicine.earlyWarning === 1" label="报警上限">
            <el-input
              v-model="medicine.upperLimit"
              type="number"
              placeholder="数量超出上限后会报警 "
            />
          </el-form-item>
          <el-form-item v-if="medicine.earlyWarning === 1" label="报警下限">
            <el-input
              v-model="medicine.lowerLimit"
              type="number"
              placeholder="数量小于下限后悔报警 "
            />
          </el-form-item>

          <el-form-item label="售价">
            <el-input
              v-model="medicine.sellingPrice"
              placeholder="请输入药品售价"
              required
            />
          </el-form-item>
          <el-form-item
            v-if="medicine.priceVOList.length == 0"
            label="会员售价"
          >
            <el-button
              icon="el-icon-plus"
              style="margin-left:15px"
              @click="handleAddH()"
            />
          </el-form-item>
          <div
            v-for="(item,i) in medicine.priceVOList"
            :key="i"
          >
            <el-form-item
              :label="(i+1)+'级会员售价'"
              prop="sellingPrice"
              label-width="100px"
            >
              <el-col :span="8">
                <el-input
                  v-model="item.sellingPrice"
                  placeholder="请输入药品售价"
                  required
                  width="80%"
                  :disabled="i+1<medicine.priceVOList.length"
                  @change="handlerChangeShou"
                />
              </el-col>
              <el-button
                v-if="i+1==medicine.priceVOList.length"
                icon="el-icon-plus"
                style="margin-left:15px"
                @click="handleH(i,1)"
              />
              <el-button
                v-if="i+1==medicine.priceVOList.length && i!==0"
                icon="el-icon-minus"
                style="margin-left:15px"
                @click="handleH(i,2)"
              />
            </el-form-item>
          </div>
          <el-form-item
            label="进价"
            required
          >
            <el-input
              v-model="medicine.purchasePrice"
              placeholder="请输入药品进价"
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="提成方式">
            <el-radio-group v-model="medicine.commissionType">
              <el-radio :label="0">
                无提成
              </el-radio>
              <el-radio :label="1">
                比例提成
              </el-radio>
              <el-radio :label="2">
                固定提成
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="medicine.commissionType === 2" label="提成数额">
            <el-input
              v-model="medicine.commissionAmount"
              placeholder="请输入药品销售提成 "
            />
          </el-form-item>
          <el-form-item v-if="medicine.commissionType === 1" label="提成比例">
            <el-input
              v-model="medicine.commission"
              placeholder="请输入药品比例提成的小数"
            />
          </el-form-item>
          <el-form-item label="规格">
            <el-input
              v-model="medicine.spec"
              placeholder="请输入规格"
            />
          </el-form-item>
          <div style="text-align:right;">
            <el-button
              type="danger"
              @click="dialogBianji=false"
            >取消</el-button>
            <el-button
              type="primary"
              @click="confirmEditorMedicine"
            >确定</el-button>
          </div>
        </el-form>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import user from '@/components/user'
import search from '@/components/search'
import mediceSelect from '@/components/medicine'
import prescriptionSelect from '@/components/prescription'
import { deepClone } from '@/utils'
import { addMedicine, getMedicines, medicineCheckInOut, updateMedicine } from '@/api/medicine'
import { addPayment } from '@/api/pay'
import { addPrescription, updatePresciption } from '@/api/prescription'
import DndList from '@/components/DndList'
import { timestampToTime } from '@/utils/time'
import { getUser } from '@/api/user'
import { commissionType } from '@/utils/role'

const defaultMedicine = {
  key: '',
  name: '',
  code: '',
  number: '',
  factory: '',
  purchasePrice: '',
  commissionType: 1,
  earlyWarning: 0,
  priceVOList: []
  // priceVOList: [{ userLevel: 1, sellingPrice: '' }]
}
const defaultprescription = {
  adminInfoVO: {},
  userInfoVO: {}
}

export default {
  components: {
    search,
    mediceSelect,
    prescriptionSelect,
    DndList,
    user
  },
  data() {
    return {
      payMethodList: [
        { label: '现金', value: 1 },
        { label: '微信', value: 2 },
        { label: '支付宝', value: 3 },
        { label: '医保卡', value: 4 }
      ],
      tabMapOptions: [
        { label: '当天', key: 'CN' },
        { label: '近一周', key: 'US' },
        { label: '近一月', key: 'JP' },
        { label: '所有', key: 'EU' }
      ],
      medicine: Object.assign({}, defaultMedicine),
      pay: { registrationFee: 0 },
      routes: [],
      dialogMedicine: false,
      medicineList: [],
      dialogVisible: false,
      dialogRuku: false,
      dialogChuku: false,
      dialogType: 'new',
      dialogPrescription: false,
      dialogBianji: false,
      dialogUser: false,
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      list1: [],
      list2: [],
      tab: 'first',
      rukuRules: {
        name: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ],
        // sellingPrice: [
        //   { required: true, message: '必填项必须填写', trigger: 'blur' }
        // ],
        purchasePrice: [
          { required: true, message: '必填项必须填写', trigger: 'blur' }
        ]
      },
      isUser: false,
      chuku: false,
      search: '',
      activeName: 'first',
      pageNum: 1, // 默认每页显示1条数据
      pageSize: 10,
      loading: false,
      totalCount: 0,
      prescription: Object.assign({}, defaultprescription),
      prescriptionId: 0,
      prescriptionNewId: '0',
      prescriptionMedicineList: [],
      payArr: [{ method: 1, amount: 0 }],
      user: {},
      level: 0,
      price: 0
    }
  },
  async created() {
    // console.log(res)
    // Mock: get all routes and roles list from server
    // this.getRoutes()
    this.getMedicine({
      pageNum: this.pageNum,
      pageSize: this.pageSize
    })
    this.list2 = deepClone(this.medicineList)
  },
  methods: {
    async getMedicine(data) {
      const res = await getMedicines(data)
      this.medicineList = res.data.list
      for (const i in this.medicineList) {
        this.medicineList[i].key = i
        this.medicineList[i].updateTime = timestampToTime(this.medicineList[i].updateTime)
        this.medicineList[i].commissionTypeC = commissionType(this.medicineList[i].commissionType)
      }
      this.totalCount = res.data.total
    },
    handleInMedicine() { // 点击入库按钮
      // this.medicine = Object.assign({}, defaultMedicine)
      this.reset()
      this.dialogRuku = true
    },
    handleOutMedicine() { // 点击出库按钮
      // this.medicine = Object.assign({}, defaultMedicine)
      // this.prescription = Object.assign({}, defaultprescription)
      // this.price = 0
      this.reset()
      this.dialogChuku = true
    },
    handleEdit(scope) { // 修改
      this.dialogType = 'edit'
      this.dialogBianji = true
      this.checkStrictly = true
      this.medicine = deepClone(scope.row)
      console.log(this.medicine)
      this.medicine.priceVOList = scope.row.medicinePriceDOList
    },
    async confirmEditorMedicine() { // 修改按钮确认修改
      delete this.medicine.updateTime
      var list = this.medicine.priceVOList
      if (list.length < 5 && list.length !== 0) { // 如果不足5 就补充到5
        for (let i = 0; i < 5; i++) {
          console.log(list[i])
          if (list[i] === undefined || list[i].sellingPrice === '') {
            list[i] = {}
            list[i].userLevel = i + 1
            console.log(list[i - 1])
            list[i].sellingPrice = list[i - 1].sellingPrice
          }
        }
      }
      // this.medicine.medicinePriceDOList = this.medicine.priceVOList
      const res = await updateMedicine(this.medicine)
      const medicineList = this.medicineList
      this.$notify({
        title: '修改成功',
        dangerouslyUseHTMLString: true,
        message: `
            <div>药品名称: ${this.medicine.name}</div>
          `,
        type: 'success'
      })
      for (let index = 0; index < medicineList.length; index++) {
        if (medicineList[index].key === this.medicine.key) {
          medicineList.splice(index, 1, Object.assign({}, this.medicine))
          break
        }
      }
      this.getMedicine({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      this.dialogBianji = false
    },
    handleDelete({ $index, row }) { // 删除操作
      this.$confirm('确定要禁用吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(row)
        row.disable = 1
        const data = {}
        data.id = row.id
        data.disable = 1
        await updateMedicine(data)
        this.medicineList[$index].disable = 1
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      })
        .catch(err => { console.error(err) })
    },
    handleDelete2({ $index, row }) { // 删除操作
      this.$confirm('确定要解除禁用吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(row)
        row.disable = 0
        const data = {}
        data.id = row.id
        data.disable = 0
        await updateMedicine(data)
        this.medicineList[$index].disable = 0
        this.$message({
          type: 'success',
          message: '解除成功!'
        })
      })
        .catch(err => { console.error(err) })
    },
    async confirmMedicine() { // 入库的确定按钮
      const _this = this
      if (this.tab === 'first') {
        this.ruku(this.medicine.id)
      } else {
        this.$refs.rukuNewForm.validate(async(valid) => {
          if (valid) {
            var list = this.medicine.priceVOList
            if (list.length < 5 && list.length > 0) { // 如果不足5 就补充到5
              for (let i = 0; i < 5; i++) {
                console.log(list[i])
                if (list[i] === undefined || list[i].sellingPrice === '') {
                  list[i] = {}
                  list[i].userLevel = i + 1
                  console.log(list[i - 1])
                  list[i].sellingPrice = list[i - 1].sellingPrice
                }
              }
            }
            console.log(this.medicine)
            const { data } = await addMedicine(this.medicine)
            // _this.ruku(data)  入库的接口，说不用调用了
            this.dialogRuku = false
            const { name } = this.medicine
            this.$notify({
              title: '入库成功',
              dangerouslyUseHTMLString: true,
              message: `
            <div>药品名称: ${name}</div>
          `,
              type: 'success'
            })
            this.getMedicine({
              pageNum: this.pageNum,
              pageSize: this.pageSize
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    async ruku(medicineId) { // 入库
      const _this = this
      const dataRU = {
        adminId: _this.$store.state.user.adminId,
        mark: _this.medicine.remark,
        medicineId: medicineId,
        price: _this.medicine.purchasePrice,
        number: parseInt(this.medicine.number),
        type: 1
      }
      await medicineCheckInOut(dataRU)
      this.dialogRuku = false
      const { name } = this.medicine
      this.$notify({
        title: '入库成功',
        dangerouslyUseHTMLString: true,
        message: `
            <div>药品名称: ${name}</div>
          `,
        type: 'success'
      })
      this.getMedicine({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
      // this.medicineList.unshift(this.medicine)
    },
    async confirmMedicineChuku(type) { // 出库的确定按钮
      const data = {}
      data.paymentDetailVOList = []
      if (this.tab === 'first') {
        data.prescriptionId = this.prescription.id
      } else {
        data.prescriptionId = this.prescriptionNewId
      }
      if (this.tab === 'first' || this.tab === 'second') {
        let num = 0
        for (const i in this.payArr) {
          num = num + parseInt(this.payArr[i].amount)
        }
        console.log(num, this.prescription.amount, this.pay.registrationFee)
        if (num !== this.price + parseInt(this.pay.registrationFee)) {
          this.$message({
            type: 'warning',
            message: '付款金额和应收金额不一致'
          })
          return
        }
      }
      // data.paymentDetailVOList.push({ method: this.pay.method, amount: this.pay.amount })
      data.paymentDetailVOList = this.payArr
      data.creator = this.$store.state.user.adminId
      data.registrationFee = this.pay.registrationFee
      data.mark = this.medicine.remark
      const res = await addPayment(data)
      this.$notify({
        title: '出库成功',
        dangerouslyUseHTMLString: true,
        message: `
          `,
        type: 'success'
      })
      this.dialogChuku = false
    },
    handleClickRuku(tab, event) { // 点击切换的时候
      this.tab = tab.name
      this.reset()
    },
    async handleClickChuku(tab, event) { // 点击切换的时候
      this.tab = tab.name
      this.reset()
      var form = {}
      this.list1 = []
      this.payArr = [{ method: 1, amount: 0 }]
      this.pay = { registrationFee: 0 }
      if (tab.name === 'second') {
        form.type = 2
        form.adminName = this.$store.state.user.adminId
        const { data } = await addPrescription(form)
        this.prescriptionNewId = data.toString()
      }
      if (tab.name === 'qita') {
        this.list1 = []
        form.type = 3
        form.adminName = this.$store.state.user.adminId
        const { data } = await addPrescription(form)
        this.prescriptionNewId = data.toString()
      }
    },
    medicineCancel() { // 取消
      this.dialogMedicine = false
    },
    selectMedicine(data) { // 选择药品
      this.medicine = data
      this.medicine.priceVOList = data.medicinePriceDOList
      this.medicine.number = 0
      this.dialogMedicine = false
    },
    prescriptionCancel() { // 取消药方的按钮
      this.dialogPrescription = false
    },
    handleSizeChange(page) { // 药品分页
      this.pageSize = page
      this.getMedicine({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    handleCurrentChange(page) { // 药品分页
      this.pageNum = page
      this.getMedicine({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    async selectPrescription(data) { // 选择药方以后
      this.prescription = data
      this.prescriptionMedicineList = data.prescriptionMedicineDTOList
      // this.payArr[0].payment = data.amount
      this.$set(this.payArr, 0, { amount: data.amount, method: 1 })
      this.price = data.amount
      this.pay.allPrice = data.amount + parseInt(this.pay.registrationFee)
      for (const i in this.prescriptionMedicineList) {
        this.prescriptionMedicineList[i].allPrice = Number(this.prescriptionMedicineList[i].sellingPrice) * Number(this.prescriptionMedicineList[i].number)
      }
      this.dialogPrescription = false
    },
    handlerChangeShou(val) {
      // this.medicine.sellingPrice = Number(val).toFixed(2)
    },
    handlerChangeJin(val) {
      this.medicine.purchasePrice = Number(val).toFixed(2)
    },
    selectList2(data) {
      this.list2 = data
    },
    async HandleSearch() {
      this.getMedicine({
        name: this.search,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    handleH(i, type) {
      if (type === 1) {
        if (!this.medicine.priceVOList[i].sellingPrice) {
          this.$message({
            type: 'warning',
            message: '价格不能为空'
          })
          return
        }
        if (this.medicine.priceVOList.length < 5) {
          this.medicine.priceVOList.push({ sellingPrice: '', userLevel: this.medicine.priceVOList.length + 1 })
        } else {
          this.$message({
            type: 'warning',
            message: '最多五个'
          })
        }
      } else {
        this.medicine.priceVOList.splice(i, 1)
      }
      this.$forceUpdate()
    },
    handleP(i) {
      console.log(i)
      if (i === 0 && this.payArr.length < 5) {
        this.payArr.push({ method: 1, payment: 0 })
      } else {
        if (i !== 0) {
          this.payArr.splice(i, 1)
        }
      }
    },
    handleAddH() {
      this.medicine.priceVOList.push({ sellingPrice: '', userLevel: this.medicine.priceVOList.length + 1 })
      this.$forceUpdate()
    },
    getPrice(price) {
      // this.payArr[0].payment = price
      this.$set(this.payArr, 0, { method: 1, amount: price })
      this.price = price
    },
    changeUser(bool) {
      console.log(bool)
      if (bool) {
        this.user = {}
      } else {
        this.user = {}
      }
    },
    async getUser() {
      console.log(this.user)
      if (!this.user.mobile) {
        return
      }
      const res = await getUser({ mobile: this.user.mobile })
      console.log(res)
      if (!res.data.list) {
        this.$message({
          type: 'warning',
          message: '暂无此会员'
        })
      } else {
        updatePresciption({ id: this.prescriptionNewId, userId: res.data.list[0].id })
        this.level = res.data.list[0].level
        this.user = res.data.list[0]
      }
    },
    handleSelectUser() {
      this.dialogUser = true
    },
    selectUser(data) {
      if (data.id) {
        this.user = data
        this.dialogUser = false
        updatePresciption({ id: this.prescriptionNewId, userId: data.id })
        this.level = data.level
      } else {
        this.$message({
          message: '需要选会员'
        }
        )
      }
    },
    cancelUser() {
      this.dialogUser = false
    },
    guahao() {
      this.pay.allPrice = parseInt(this.pay.registrationFee) + this.price
      this.$set(this.payArr, 0, { method: 1, amount: this.pay.allPrice })
    },
    reset() {
      this.medicine = Object.assign({}, defaultMedicine)
      this.medicine.priceVOList = []
      this.prescription = Object.assign({}, defaultprescription)
      this.payArr = [{ method: 1, amount: 0 }]
      this.price = 0
      this.pay = Object.assign({}, this.$data.pay)
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}

.medicine-input .el-input__inner {
  cursor: pointer;
}
.select-medicine-dialog {
  // width: 100%;
  height: 90vh;
  overflow: auto;
}
</style>
